package club.banyuan.demo.file;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;

/**
 * @author chencong
 * @date 2020/12/11 上午9:25
 */
public class Server {
    public static void main(String[] args) throws Exception {
        System.out.println("服务端启动成功");
        ServerSocket ss = new ServerSocket(54188);
        while (true) {
            Socket socket = ss.accept();
            new ServerThread(socket).start();
        }
    }
}

class ServerThread extends Thread {
    Socket socket;

    public ServerThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            //从管道中拿到字节输入流
            InputStream is = socket.getInputStream();
            //把字节输入流包装成缓冲字节输入流
            BufferedInputStream bis = new BufferedInputStream(is);
            //新建一个缓冲字节输出流,流向服务器文件夹
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(Constants.SERVER_DIR + UUID.randomUUID() ));
            //把字节输入流传来的数据全部写到服务器文件夹
            byte[] buffer = new byte[1024];
            int len;
            while ((len = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            bos.close();
            System.out.println(socket.getRemoteSocketAddress()+"上传的文件已保存");
            //给客户端发送消息,告诉客户端数据接收成功
            PrintStream ps = new PrintStream(socket.getOutputStream());
            ps.println("我是陈聪的服务器端,你发过来的数据我已经接收到,谢谢使用!");
            ps.flush();
            //服务器端可以休眠5秒后死掉,确保回复的消息可以发送完毕
            Thread.sleep(5000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
